<script setup lang="ts">
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import { MessageProps } from './type'
import Icon from '../Icon/Icon.vue'
import RenderVnode from '../Common/RenderVnode'
import { getLastBottomOffset, getLastInstance } from './method'
import useEventListener from '../../hooks/useEventListener'
const prevInstance = getLastInstance()
console.log('prev', prevInstance)
const props = withDefaults(defineProps<MessageProps>(), {
  type: 'info',
  duration: 3000,
  offset: 20,
  transitionName:'fade-up'
})
const visible = ref(false)
// watch(visible, (newValue) => {
//   if (!newValue) {
//     props.onDestory()
//   }
// })
function destroyComponent () {
  props.onDestory()
}
function updateHeight() {
  height.value = messageRef.value!.getBoundingClientRect().height
}
const messageRef = ref<HTMLElement>()
//计算偏移高度
// 这个div的高度
const height = ref(0)
// 上一个实例最下面的数字坐标,第一个是0
const lastOffset = computed(() => getLastBottomOffset(props.id))
// 这个元素应使用的top
const topOffset = computed(() => props.offset + lastOffset.value)
// 为下一个元素提供bottom
const bottomOffset = computed(() => height.value + topOffset.value)
const cssStyle = computed(() => ({
  top: topOffset.value + 'px',
  zIndex: props.zIndex
}))
let timer: any
function startTimer() {
  if (!props.duration) return
  timer = setTimeout(() => {
    visible.value = false
  }, props.duration)
}
function clearTimer() {
  clearTimeout(timer)
}
onMounted(async () => {
  visible.value = true
  startTimer()
  // await nextTick()
  // height.value = messageRef.value!.getBoundingClientRect().height
})
function keydown(e: Event) {
  const event = e as KeyboardEvent
  if (event.code === 'Escape') {
    visible.value = false
  }
}
useEventListener(document, 'keydown', keydown)
defineExpose({
  bottomOffset,
  visible
})
</script>

<template>
  <transition :name="transitionName" 
@afterLeave="destroyComponent"
@enter="updateHeight"
  >
    <div
      ref="messageRef"
      :style="cssStyle"
      @mouseenter="clearTimer"
      @mouseleave="startTimer"
      class="vk-message"
      v-show="visible"
      :class="{ [`vk-message--${type}`]: type, 'is-close': showClose }"
      role="alert">
      <div class="vk-message__content">
        <slot>
          <RenderVnode :vNode="message" v-if="message" />
        </slot>
      </div>
      <div class="vk-message__close" v-if="showClose">
        <Icon icon="xmark" @click.stop="visible = false"></Icon>
      </div>
    </div>
  </transition>
</template>

<style scoped></style>
